<template>
  <div class="page-login">
    <el-form :model="ruleForm"
             :rules="rules"
             ref="ruleForm" label-position="left" label-width="0px"
             class="card-box login-form">
      <div class="company">
        <el-button @click="handleCompany" type="text">守望领域保险营销平台</el-button>
      </div>

      <h3 class="title">后台管理平台</h3>
      <el-form-item prop="name">
        <el-input type="text" v-model="ruleForm.username" placeholder="账号">
          <i slot="prefix" class="el-input__icon fa fa-user"> </i>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model="ruleForm.password" placeholder="密码" @keyup.enter.native="handleSubmit">
          <i slot="prefix" class="el-input__icon fa fa-key"> </i>
        </el-input>
      </el-form-item>

      <el-form-item prop="phone" v-show="!wantLogin">
        <el-input type="phone" v-model="ruleForm.phone" placeholder="手机">
          <i slot="prefix" class="el-input__icon fa fa-phone"> </i>
        </el-input>
      </el-form-item>

      <el-form-item prop="email" v-show="!wantLogin">
        <el-input type="email" v-model="ruleForm.email" placeholder="邮箱">
          <i slot="prefix" class="el-input__icon fa fa-envelope-square"> </i>
        </el-input>
      </el-form-item>

      <el-form-item prop="code" class="code-input">
        <el-input
          ref="code"
          v-model="ruleForm.code"
          prefix-icon="el-icon-lock"
          placeholder="验证码"
          name="code"
          type="text"
          autocomplete="off"
          style="width: 50%"
          @keyup.enter.native="handleSubmit" />
        <img :src="imageCode" alt="code" class="code-image" @click="handleRequestCodeImage">
      </el-form-item>

      <el-checkbox v-model="remember" checked style="margin:0 0 1rem 0">记住密码</el-checkbox>
      <el-form-item>
        <el-button v-if="wantLogin" type="primary" style="width:100%" @click="handleSubmit" :loading="isLoading">登录
        </el-button>
        <el-button v-else type="danger" style="width:100%" @click="handleSubmit">注册</el-button>
      </el-form-item>

      <el-form-item>
      <span>{{wantLogin? '没有账号' : '已有账号'}}
        <el-button @click="handleChagne" type="text" v-bind:class="{'register-btn-text': wantLogin}">
          {{wantLogin? '去注册' : '去登录'}}
        </el-button>
      </span>
      </el-form-item>
    </el-form>
  </div>

</template>

<script type="text/ecmascript-6" >
import { register, getCodeImage } from '../api/front'
import { mapActions } from 'vuex'
import { hexMd5 } from '../utils/security/md5'
import { getObject, setObject } from '../utils/cookie'
import { randomNum } from '../utils/random'

export default {
  data () {
    let validatePhone = (rule, value, callback) => {
      if (this.wantLogin) {
        callback()
        return
      }
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (value.length !== 11) {
        callback(new Error('需输入11位手机号'))
      } else {
        callback()
      }
    }
    let validateEmail = (rule, value, callback) => {
      if (this.wantLogin) {
        callback()
        return
      }
      if (value === '') {
        callback(new Error('请输入电子邮箱'))
      } else {
        callback()
      }
    }
    return {
      ruleForm: {
        username: '',
        password: '',
        phone: '',
        email: '',
        code: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 18, message: '请输入长度在6到18位的密码', trigger: 'blur' }
        ],
        phone: [
          { validator: validatePhone, trigger: 'blur' }
        ],
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ]
      },
      isLoading: false,
      remember: true,
      wantLogin: true,
      styleGoBtn: {
        color: this.wantLogin ? '#409EFF' : '#f56c6c'
      },
      randomStr: undefined,
      imageCode: undefined
    }
  },
  created () {
    this.handleRequestCodeImage()
  },
  mounted () {
    let rememberObj = getObject('remember')
    if (rememberObj) {
      this.remember = true
      let obj = JSON.parse(rememberObj)
      this.ruleForm.username = obj.n
      this.ruleForm.password = obj.p
    }
  },
  methods: {
    ...mapActions([
      'USER_LOGIN', 'SET_LOGIN_TOKEN'
    ]),
    handleCompany () {
      window.open('http://www.360safeschool.com')
    },
    handleChagne () {
      this.wantLogin = !this.wantLogin
    },
    handleReset () {
      this.$refs.ruleForm.resetFields()
    },
    handleRequestCodeImage () {
      this.randomStr = randomNum(24, 16)
      getCodeImage(this.randomStr).then(response => {
        return 'data:image/png;base64,' + btoa(new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte), ''))
      }).then(data => {
        this.imageCode = data
      })
    },
    handleSubmit () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.wantLogin ? this.doLogin() : this.doRegister()
          // console.log('handle login ok')
        } else {
          // console.log('handle login error')
          return false
        }
      })
    },
    doRegister () {
      let data = {
        username: this.ruleForm.username,
        password: hexMd5(this.ruleForm.password),
        phone: this.ruleForm.phone,
        email: this.ruleForm.email
      }
      register(data).then(response => {
        let success = parseInt(response.code) === 0
        if (success) {
          this.ruleForm.password = ''
          this.ruleForm.phone = ''
          this.ruleForm.email = ''
          this.wantLogin = true
          this.$message.success('注册成功')
        }
      })
    },
    doLogin () {
      // console.log('doLogin')
      this.isLoading = true
      let data = {
        username: this.ruleForm.username,
        password: hexMd5(this.ruleForm.password), // hexMd5(this.ruleForm.password)
        code: this.ruleForm.code,
        key: this.randomStr
      }
      this.USER_LOGIN(data).then(response => {
        if (this.remember) {
          let rememberObj = {
            n: this.ruleForm.username,
            p: this.ruleForm.password
          }
          setObject('remember', rememberObj)
        } else {
          setObject('remember', null)
        }
        this.isLoading = false
        if (response.code && parseInt(response.code) !== 0) {
          // console.log('return')
          return
        }
        this.SET_LOGIN_TOKEN(response) // set login token
        let redirect = this.$route.query.redirect
        if (!redirect) {
          redirect = '/'
        }
        this.$router.push(redirect)
      }).catch(() => {
        this.isLoading = false
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" >
  @import "assets/styles/login.scss";
</style>
